package com.philosophy.web.domain.generate;

import com.philosophy.config.GenerateSnowIdConfig;
import org.springframework.stereotype.Component;

/**
 * <p>
 * 根据雪花Id的方式映射短链接
 * </p>
 * <p>
 * 时间戳+机器id+序列号
 * </p>
 *
 * @author philosophy
 */
@Component
public class GenerateShortUrlBySnow extends AbstractGenerateShortUrl {
    /**
     * 起始的时间戳
     */
    private final static long START_STAMP = 1653971162771L;

    /**
     * 机器标识占用的位数
     */
    private final static long MACHINE_BIT = 6;
    /**
     * 序列号占用的位数
     */
    private final static long SEQUENCE_BIT = 12;


    /**
     * 每一部分的最大值
     */
    private final static long MAX_MACHINE_NUM = (long) Math.pow(2, MACHINE_BIT);
    private final static long MAX_SEQUENCE = (long) Math.pow(2, SEQUENCE_BIT);

    /**
     * 每一部分向左的位移
     */
    private final static long MACHINE_LEFT = SEQUENCE_BIT;
    private final static long TIMESTAMP_LEFT = SEQUENCE_BIT + MACHINE_BIT;

    /**
     * Value("${snow.machine.id}")  机器标识
     */
    private final long machineId;
    /**
     * 序列号
     */
    private long sequence = 0L;
    /**
     * 上一次时间戳
     */
    private long lastStamp = -1L;

    public GenerateShortUrlBySnow(GenerateSnowIdConfig generateSnowIdConfig) {
        this.machineId = generateSnowIdConfig.getId();
        if (machineId > MAX_MACHINE_NUM || machineId < 0) {
            throw new IllegalArgumentException("machineId 不能大于 MAX_MACHINE_NUM 或者小于 0");
        }
    }

    @Override
    protected long getStrIdentity(String str) {
        return nextId();
    }

    @Override
    protected String getSalt() {
        return "";
    }


    /**
     * 产生下一个ID
     */
    public synchronized long nextId() {
        long currStamp = getNewTimestamp();
        if (currStamp < lastStamp) {
            throw new RuntimeException("Clock moved backwards.  Refusing to generate id");
        }

        if (currStamp == lastStamp) {
            //相同毫秒内，序列号自增
            sequence = (sequence + 1) % MAX_SEQUENCE;
            //同一毫秒的序列数已经达到最大
            if (sequence == 0L) {
                currStamp = getNextMill();
            }
        } else {
            //不同毫秒内，序列号置为0
            sequence = 0L;
        }

        lastStamp = currStamp;
        //时间戳部分,//机器标识部分,//序列号部分
        return (currStamp - START_STAMP) << TIMESTAMP_LEFT | machineId << MACHINE_LEFT | sequence;
    }

    private long getNextMill() {
        long mill = getNewTimestamp();
        while (mill <= lastStamp) {
            mill = getNewTimestamp();
        }
        return mill;
    }

    private long getNewTimestamp() {
        return System.currentTimeMillis();
    }
}
